<template>
    <d2-mng-page
        :filename="filename"
        @qry-data="qryData"
        @create="onCreate"
        create-access-rule="user-add"
        @update="onUpdate"
        update-access-rule="user-add"
        @del="onDel"
        del-access-rule="user-add"
        :page="page"
        :form-mode.sync="formMode"
        :dialog-form-visible.sync="dialogFormVisible"
        :select-rows="selectRows"
        :show-option-box="true">

        <!--搜索-->
        <el-form slot="search-inner-box" :inline="true" :model="searchForm" :rules="searchRules" ref="ruleSearchForm"
                 class="demo-form-inline">
            <el-form-item label="状态" prop="status">
                <el-select size="small" v-model="searchForm.status" placeholder="请选择" :required="true"
                           @change="onChangeSearchChannel">
                    <el-option
                        v-for="item in statusOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
                <el-input
                    size="small"
                    placeholder="请输入用户名"
                    v-model="searchForm.username">
                </el-input>
            </el-form-item>
            <el-form-item label="手机号">
                <el-input
                    size="small"
                    placeholder="请输入手机号"
                    v-model="searchForm.mobile">
                </el-input>
            </el-form-item>
            <el-form-item label="邮箱">
                <el-input
                    size="small"
                    placeholder="请输入邮箱"
                    v-model="searchForm.email">
                </el-input>
            </el-form-item>
            <el-form-item class="search-inner-btn-box">
                <el-button size="small" type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
                <el-button size="small" icon="el-icon-refresh" @click="onCancelSubmit">重置</el-button>
            </el-form-item>
        </el-form>

        <!--提示框-->
        <ul slot="hint-msg-box">
            <li>`用户名`必须唯一</li>
            <li>不能删除登录用户记录</li>
        </ul>
        <el-button v-has="'user-add'" slot="option-box-attch-but" size="small"
                   @click="onClickModifyPwd">修改用户密码
        </el-button>

        <!--表格-->
        <el-table
            ref="table"
            :data="page.records"
            stripe
            height="630"
            border
            @selection-change="handleSelectionChange"
            style="width: 100%">
            <el-table-column type="expand">
                <template slot-scope="props">
                    <el-form label-position="top" inline class="demo-table-expand">
                        <el-form-item label="授权角色">
                            <el-tag v-for="role in props.row.roles" v-bind:key="role.id" style="margin-right: 10px">
                                {{role.name}}
                            </el-tag>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column
                type="selection"
                width="60">
            </el-table-column>
            <el-table-column
                prop="username"
                label="用户名">
            </el-table-column>
            <el-table-column
                prop="mobile"
                label="手机号">
            </el-table-column>
            <el-table-column
                prop="email"
                label="邮箱">
            </el-table-column>
            <el-table-column
                prop="createTime"
                label="创建时间">
            </el-table-column>
        </el-table>

        <!--添加-->
        <el-form slot="form" :model="form" :rules="rules" ref="form" @submit.native.prevent>
            <div class="dialog-form-submit-container">
                <el-form-item label="用户名" :required="true" prop="username">
                    <el-input v-model="form.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" :required="true" prop="password" v-if="formMode === 'add'">
                    <el-input v-model="form.password" autocomplete="off" type="password"></el-input>
                </el-form-item>
                <el-form-item label="资源授权" :required="true" prop="roleIds">
                    <el-select v-model="form.roleIds" multiple placeholder="请选择">
                        <el-option
                            v-for="item in rolesOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="form.mobile" autocomplete="off" type="tel"></el-input>
                </el-form-item>

                <el-form-item label="邮箱">
                    <el-input v-model="form.email" autocomplete="off" type="email"></el-input>
                </el-form-item>

                <div class="dialog-form-submit-inner-container">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" native-type="submit" @click="onSubmitForm">确 定</el-button>
                </div>
            </div>
        </el-form>

        <!--修改密码-->
        <el-dialog
            title="修改密码"
            :visible.sync="dialogModifyPwdFormVisible"
            width="40%"
            :modal="true">
            <el-form :model="form" :rules="rulesModifyPwd" ref="modifyPwdForm" @submit.native.prevent>
                <div class="dialog-form-submit-container">
                    <el-form-item label="用户名" :required="true" prop="username">
                        <el-input v-model="form.username" autocomplete="off" :disabled="true"/>
                    </el-form-item>
                    <el-form-item label="密码" :required="true" prop="password">
                        <el-input v-model="form.password" autocomplete="off"/>
                    </el-form-item>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogModifyPwdFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="onSubmitModifyPwdForm">确 定</el-button>
            </div>
        </el-dialog>
    </d2-mng-page>
</template>

<script>
import _ from 'lodash'
// import { mapState } from 'vuex'
import { del, getUserList, pwd, userSR } from '@api/user'
import { list } from '@api/role'

export default {
  name: 'mngauth-role',

  data () {
    return {
      filename: __filename,
      rolesOptions: [],
      formMode: 'add',
      dialogFormVisible: false,
      dialogModifyPwdFormVisible: false,
      rulesModifyPwd: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ]
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        roleIds: [{ required: true, message: '请选择授权角色，可以多选', trigger: 'change' }]
      },
      form: {
        id: '',
        username: '',
        password: '',
        mobile: '',
        email: '',
        roleIds: []
      },
      selectRows: [],
      page: {
        records: [],
        total: 0,
        size: 10,
        current: 1
      },
      statusOptions: [
        {
          value: '0',
          label: '已启用'
        }, {
          value: '1',
          label: '已禁用'
        }
      ],
      searchRules: {
        // username: [
        //   { required: true, message: '请输入姓名', trigger: 'blur' }
        // ]
      },
      searchForm: {
        status: '',
        username: '',
        mobile: '',
        email: ''
      }
    }
  },
  computed: {},
  created () {
    this.onCancelSubmit()
    this.getRoleList()
  },
  methods: {

    /* 角色 */
    getRoleList () {
      list().then(async res => {
        this.rolesOptions = res
      })
    },

    /* 修改密码 */
    onSubmitModifyPwdForm () {
      this.$refs.modifyPwdForm.validate((valid) => {
        if (valid) {
          pwd(this.form).then(res => {
            this.qryData()
          }).then(() => {
            this.dialogModifyPwdFormVisible = false
          })
        }
      })
    },
    onClickModifyPwd () {
      if (!_.isEmpty(this.selectRows) && this.selectRows.length === 1) {
        this.form = this.selectRows[0]
        this.form.password = ''
        this.dialogModifyPwdFormVisible = true
      } else {
        this.$notice.toast('请选择一条需要编辑的记录', { type: 'warning' })
      }
    },

    /* table */
    qryData () {
      const params = new URLSearchParams()
      if (this.page.current) {
        params.append('current', this.page.current)
      }
      if (this.page.size) {
        params.append('size', this.page.size)
      }
      if (this.searchForm.username) {
        params.append('username', this.searchForm.username)
      }
      if (this.searchForm.mobile) {
        params.append('mobile', this.searchForm.mobile)
      }
      if (this.searchForm.email) {
        params.append('email', this.searchForm.email)
      }
      if (this.searchForm.status) {
        params.append('status', this.searchForm.status)
      }
      getUserList(params).then(async res => {
        this.page = res
      })
    },
    handleSelectionChange (rows) {
      this.selectRows = rows
    },

    /* 搜索 */
    onChangeSearchChannel (idx) {
      this.searchForm.status = this.statusOptions[idx].value
      this.qryData()
    },
    onSearch () {
      this.$refs.ruleSearchForm.validate((valid) => {
        if (valid) {
          this.qryData()
        }
      })
    },
    onCancelSubmit () {
      if (this.$refs.ruleSearchForm) {
        this.$nextTick(() => {
          this.$refs.ruleSearchForm.resetFields()
        })
      }
      this.qryData()
    },

    /* 删除 */
    onDel () {
      const ids = []
      ids.push(this.selectRows.map((el) => {
        return el.id
      }))

      if (ids.length > 0) {
        const params = new URLSearchParams()
        params.append('ids', ids)
        this.$confirm('删除用户?', '提示', {
          type: 'warning'
        }).then(() => {
          del(params).then(async res => {
            this.qryData()
            this.selectRows = []
          })
        })
      }
    },

    /* 添加 */
    onCreate () {
      this.form = {
        id: '',
        username: '',
        password: '',
        mobile: '',
        email: '',
        roleIds: []
      }
    },

    /* 修改 */
    onUpdate (item) {
      this.dialogFormVisible = true
      this.form.password = item.password
      this.form.id = item.id
      this.form.mobile = item.mobile
      this.form.username = item.username
      this.form.roleIds = item.roles.map(function (role) { return role.id })
      this.form.email = item.email
    },

    onSubmitForm () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = new URLSearchParams()
          params.append('roleIds', this.form.roleIds)
          userSR(this.form, params).then(async res => {
            this.dialogFormVisible = false
            this.qryData()
          })
        }
      })
    }
  }

}
</script>
